/* eslint-disable no-unused-vars */
import api from '@/api/index.js'
import { post, get, From, postJson,deleteData } from '@/api/request'//真实请求
const state = {
    cartList: [],
}

const mutations = {
    GETCARTLIST(state, data) {
        state.cartList = data
    }
}

const actions = {
    getCartList({ commit }, data) {//获取购物车列表
        return new Promise((resolve, reject) => {
            get(api.cartList).then(res => {
                if (res.code == 200) {
                    commit('GETCARTLIST', res.data)
                    resolve(res.data)
                }
            }).catch(err => {
                reject(err)
            })
        })
    },
    deleteList({ commit }, skuId) {//删除购物车
        return new Promise((resolve, reject) => {
            deleteData(`${api.deleteList}/${skuId}`).then(res => {
               if(res.code == 200){
                   resolve(res.ok)
               }
            }).catch(err => {
                reject(err)
            })
        })
    },
    updateChecked({ commit }, {skuId,isChecked}) {//选中购物车
        return new Promise((resolve, reject) => {
            get(`${api.isCheckList}/${skuId}/${isChecked}`,{},false).then(res => {
               if(res.code == 200){
                   resolve(res.ok)
               }
            }).catch(err => {
                reject(err)
            })
        })
    },
    deleteAllCart({dispatch,state}) {//删除选中的购物车
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item => {
            let result= item.isChecked==1? dispatch('deleteList',item.skuId):''
            PromiseAll.push(result)
        })
        return Promise.all(PromiseAll)//有一个失败就是失败,全部成功就是成功
    },
    updateAllChecked({dispatch,state},isChecked) {//全选
        let PromiseAll = []
        state.cartList[0].cartInfoList.forEach(item => {
            let result= dispatch('updateChecked',{skuId:item.skuId,isChecked})//将所有的物品的isChecked都变为1
            PromiseAll.push(result)
        })
        return Promise.all(PromiseAll)//有一个失败就是失败,全部成功就是成功
    }
}

export default {
        state,
        mutations,
        actions
    }
